"""
题库系统 - 工具类
提供题目导入导出等功能
"""
import pandas as pd
from django.core.files.uploadedfile import InMemoryUploadedFile
from io import BytesIO
import json

from .models import Question, QuestionBank


class QuestionImporter:
    """题目导入器"""

    @staticmethod
    def from_excel(file_obj, question_bank):
        """从Excel文件导入题目"""
        try:
            df = pd.read_excel(file_obj)
            questions = []

            for index, row in df.iterrows():
                # 这里需要根据实际的Excel格式来解析
                question_data = {
                    'title': row.get('title', ''),
                    'stem': row.get('stem', ''),
                    'type': row.get('type', 'choice'),
                    'difficulty': row.get('difficulty', 'medium'),
                    'points': row.get('points', 5),
                    'options': row.get('options', ''),
                    'answer': row.get('answer', ''),
                    'subject': row.get('subject', ''),
                    'chapter': row.get('chapter', ''),
                    'tags': row.get('tags', ''),
                    'keywords': row.get('keywords', ''),
                }
                questions.append(question_data)

            return questions
        except Exception as e:
            raise Exception(f"Excel文件解析失败: {str(e)}")

    @staticmethod
    def from_csv(file_obj, question_bank):
        """从CSV文件导入题目"""
        try:
            df = pd.read_csv(file_obj)
            questions = []

            for index, row in df.iterrows():
                question_data = {
                    'title': row.get('title', ''),
                    'stem': row.get('stem', ''),
                    'type': row.get('type', 'choice'),
                    'difficulty': row.get('difficulty', 'medium'),
                    'points': row.get('points', 5),
                    'options': row.get('options', ''),
                    'answer': row.get('answer', ''),
                    'subject': row.get('subject', ''),
                    'chapter': row.get('chapter', ''),
                    'tags': row.get('tags', ''),
                    'keywords': row.get('keywords', ''),
                }
                questions.append(question_data)

            return questions
        except Exception as e:
            raise Exception(f"CSV文件解析失败: {str(e)}")


class QuestionExporter:
    """题目导出器"""

    @staticmethod
    def to_excel(questions, include_answers=False, include_analysis=False):
        """导出到Excel"""
        data = []
        for question in questions:
            row = {
                'ID': question.id,
                '标题': question.title,
                '题目内容': question.stem,
                '类型': question.get_type_display(),
                '难度': question.get_difficulty_display(),
                '分数': question.points,
                '科目': question.subject,
                '章节': question.chapter,
                '标签': ','.join(question.tags) if question.tags else '',
                '关键词': question.keywords,
            }

            if include_answers:
                row['答案'] = question.answer
                row['选项'] = question.options

            if include_analysis:
                row['解析'] = question.analysis
                row['解释'] = question.explanation

            data.append(row)

        df = pd.DataFrame(data)

        # 创建Excel文件
        output = BytesIO()
        with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
            df.to_excel(writer, sheet_name='题目', index=False)

        output.seek(0)
        return output

    @staticmethod
    def to_csv(questions, include_answers=False, include_analysis=False):
        """导出到CSV"""
        data = []
        for question in questions:
            row = {
                'ID': question.id,
                '标题': question.title,
                '题目内容': question.stem,
                '类型': question.get_type_display(),
                '难度': question.get_difficulty_display(),
                '分数': question.points,
                '科目': question.subject,
                '章节': question.chapter,
                '标签': ','.join(question.tags) if question.tags else '',
                '关键词': question.keywords,
            }

            if include_answers:
                row['答案'] = question.answer
                row['选项'] = question.options

            if include_analysis:
                row['解析'] = question.analysis
                row['解释'] = question.explanation

            data.append(row)

        df = pd.DataFrame(data)

        # 创建CSV文件
        output = BytesIO()
        df.to_csv(output, index=False, encoding='utf-8-sig')

        output.seek(0)
        return output

    @staticmethod
    def to_json(questions, include_answers=False, include_analysis=False):
        """导出到JSON"""
        data = []
        for question in questions:
            item = {
                'id': question.id,
                'title': question.title,
                'stem': question.stem,
                'type': question.get_type_display(),
                'difficulty': question.get_difficulty_display(),
                'points': question.points,
                'subject': question.subject,
                'chapter': question.chapter,
                'tags': question.tags,
                'keywords': question.keywords,
                'created_at': question.created_at,
            }

            if include_answers:
                item['answer'] = question.answer
                item['options'] = question.options

            if include_analysis:
                item['analysis'] = question.analysis
                item['explanation'] = question.explanation

            data.append(item)

        return json.dumps(data, ensure_ascii=False, indent=2)